package com.fone.player.online.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.Request;
import com.fone.player.client.RstSerializer;
import com.fone.player.client.SearchRst;
import com.fone.player.client.SpecllistRst;
import com.fone.player.client.SpecllistRst.Cnt;
import com.fone.player.client.SpecllistRst.Col;
import com.fone.player.entity.LiveInfo;
import com.fone.player.entity.RedirectInfo;
import com.fone.player.entity.SearchInfo;
import com.fone.player.online.adapter.LiveAdapter;
import com.fone.player.play.PlayerFrom;
import com.fone.player.util.Activity2poster;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.FoneWebViewClient;
import com.fone.player.util.L;
import com.fone.player.util.ScreenUtil;
import com.fone.player.util.SharedPreferenceOnline;
import com.fone.player.util.WebViewAction;
import com.fone.player.view.FilmSetSearch;
import com.fone.player.view.PostersView;
import com.fone.player.view.FilmSetSearch.OnSearcherListener;
import com.fone.player.widget.xlistview.XListView;
import com.fone.player.widget.xlistview.XListView.IXListViewListener;

/**
 * 直播模板Activity。
 */
public class LiveActivity extends BaseActivity implements IXListViewListener {
	/** 日志标签 */
	private static final String TAG = "LiveActivity";

	private ImageView tagView;
	private Button mLeftBt;
	private Button mRightBt;
	private TextView mTitleTv;
	private XListView mListView;
	private FilmSetSearch filmSearch;
	private PostersView poster;
	
	private WebView mWebView;

	private LiveAdapter adapter;
	
	private RstSerializer rstSerializer;
	private SharedPreferenceOnline sp;
	
	private SpecllistRst  t;
	
	private String localStr;
	
	private String url;
	private String name;
	private String id;
	
	private String shost;
	private String host;
	private String clid;
	private String nurl;
	
	private String webUrl;
	
	private String category;
	private String country;
	private String year;
	
	private int page = 1;
	private int webHight;
	
	private List<LiveInfo> liveList = new ArrayList<LiveInfo>();

	private static final int SUCCESS = 0;
	private static final int FAILURE = 1;

	//是否第一次加载
	private boolean isFirst = true;
	//是否为栏目数据
	private boolean isColumn = true;
	//是否为固定url，即来自于Intent传递的url;
	private boolean isFix = true;
	
	private final int UPDATELOCAL = 0;
	private final int UPDATESERVER = 1;
	
	private Handler mHandler = new Handler(){
	
			@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			 super.handleMessage(msg);
			 switch (msg.what) {
				
				case UPDATELOCAL:
					isFirst = true;
					updateLive(true, t);
					break;

				case UPDATESERVER:
					isFirst = true;
//					initColumnData(url);
					onRefresh();
					break;

				default:
					break;
				}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_live);
		
		getIntentData();
		initView();
		
		initData();
//		initColumnData(url);
	}
	
	/**
	 * 获得Intent传递值
	 */
	private void getIntentData(){
		Intent intent = getIntent();
		url = intent.getStringExtra("url");
		name = intent.getStringExtra("name");
		id = intent.getStringExtra("id");
	}
	
	/**
	 * 布局控件初始化
	 */
	private void initView() {
		//标题栏
		mLeftBt = (Button) findViewById(R.id.common_title_left_bt);
		mRightBt = (Button) findViewById(R.id.common_title_right_bt);
		mTitleTv = (TextView) findViewById(R.id.common_left_title_tv);
		
		mLeftBt.setOnClickListener(new BtnOnClicker());
		mRightBt.setVisibility(View.GONE);
		mTitleTv.setVisibility(View.VISIBLE);
		mTitleTv.setText(name);

		//ListView
		mListView = (XListView) findViewById(R.live.list);
		
		mListView.setPullLoadEnable(false);
		mListView.setPullRefreshEnable(true);
		mListView.setEnableDragLoadMore(false);
		mListView.setXListViewListener(this);
//		mListView.setOnScrollListener(this);
		
		//分类检索线
		tagView = (ImageView) findViewById(R.live.tagview);
		filmSearch = (FilmSetSearch) findViewById(R.live.filesearch);
		filmSearch.setOnSearcherListener(new SearchListener());
		
		//海报页
		posterNewInstance();
		if(isFirst){
			mListView.addHeaderView(poster);
		}

		// Web专题页
		webNewInstance();
		if(isFirst){
			mListView.addHeaderView(mWebView);
		}
		
		adapter = new LiveAdapter(LiveActivity.this, shost, liveList);
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(new LiveItemClicker());
	}
	
	private PostersView posterNewInstance(){
		if(poster == null){
			poster = new PostersView(LiveActivity.this);
			poster.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, ScreenUtil.dp2px(126)));
			poster.setVisibility(View.INVISIBLE);
		}
		return poster;
	}
	
	private WebView webNewInstance(){
		if(mWebView == null){
			mWebView = new WebView(ApplicationManage.getGlobalContext());
			mWebView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, 1));
			mWebView.setBackgroundColor(0);
			// 设置WebView属性，能够执行Javascript脚本
			mWebView.getSettings().setJavaScriptEnabled(true);
			mWebView.setWebViewClient(new FoneWebViewClient());
			mWebView.addJavascriptInterface(new WebViewAction(LiveActivity.this), "Fone");
			mWebView.setVisibility(View.INVISIBLE);
		}
		return mWebView;
	}
	
	private void initData(){
		
		//当缓存为空时，向服务器申请数据
//		if(TextUtils.isEmpty(localStr)){
//			mHandler.sendEmptyMessage(UPDATESERVER);
//		}else{
			
			new Thread(new Runnable() {

				@Override
				public void run() {
					rstSerializer = new RstSerializer();
					sp = new SharedPreferenceOnline(LiveActivity.this, id);
					localStr = sp.getData();
					
					// TODO Auto-generated method stub
					if(isSerializerOK(localStr)){
						mHandler.sendEmptyMessage(UPDATELOCAL);
						//当有网且缓存数据超时，重新申请数据
						if(isTimeOut(sp.getTime(), System.currentTimeMillis())){
							mHandler.sendEmptyMessage(UPDATESERVER);
						}
					}else{
						mHandler.sendEmptyMessage(UPDATESERVER);
					}
				}
			}).start();
			
//		}
	}
	
	private boolean isSerializerOK(String data){
		try {
			t = (SpecllistRst)rstSerializer.fromString(SpecllistRst.class, data);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/** 
	 * 判断缓存是否过期
	 */
	private boolean isTimeOut(Long sptime, Long currenttime){
		long num = (long)((currenttime -sptime)/60000);
		return num > 15;
	}
	
	/** 
	 * 申请栏目数据
	 */
	private boolean initColumnData(String path) {
		// 如果没有网络，则不向服务器申请数据
		if (FoneUtil.isNetOkWithToast(LiveActivity.this)) {
			Request.getInstance().specllist(FoneUtil.onlineUrl(path), new LiveCallBack());
			L.v(TAG, "initColumnData", FoneUtil.onlineUrl(path));
			return true;
		}else{
			return false;
		}
	}
	
	/** 
	 * 申请搜索数据
	 */
	private boolean initSearchData(int page) {
		// 如果没有网络，则不向服务器申请数据
		if (FoneUtil.isNetOkWithToast(LiveActivity.this)) {
			SearchInfo info = new SearchInfo();
			info.columnid = clid;
			info.typename = category;
			info.area = country;
			info.year = year;
			Request.getSearchInstance(LiveActivity.this).search(4, "", page, "0", "0", "0", info, new SearchCallBack());
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 栏目数据返回处理
	 */
	private class LiveCallBack implements Callback<SpecllistRst> {

		@Override
		public void onSuccess(SpecllistRst t) {
			mListView.stopRefresh();
			mListView.stopLoadMore();
			
			updateLive(false, t);
		}

		@Override
		public void onFailure(Error error) {
			mListView.stopRefresh();
			mListView.stopLoadMore();
			
			L.v(TAG, "HorizontalCallBack", "-onFailure-" + error.toString());
			
			// 数据返回不正确 不允许上拉加载更多,允许下拉刷新
			mListView.setPullRefreshEnable(false);
			mListView.setEnableDragLoadMore(false);
			mListView.setPullRefreshEnable(true);
		}

	}

	/**
	 * 搜索数据返回处理
	 */
	private class SearchCallBack implements Callback<SearchRst>{

		@Override
		public void onSuccess(SearchRst t) {
			// TODO Auto-generated method stub
			mListView.stopRefresh();
			mListView.stopLoadMore();
			
			L.v(TAG, "SearchCallBack", "-onSuccess-" + t.result);

			if (t.result == SUCCESS) {
				if(isFirst){
					liveList.clear();
					mListView.removeHeaderView(poster);
					mListView.removeHeaderView(mWebView);
					
				}
				frashSearchListView(t);
				loadNextPage(t);
				isFirst = false;
				
			} else {

				// 数据返回不正确 不允许上拉加载更多,允许下拉刷新
				mListView.setPullRefreshEnable(false);
				mListView.setEnableDragLoadMore(false);
				mListView.setPullRefreshEnable(true);
			}
		}

		@Override
		public void onFailure(Error error) {
			// TODO Auto-generated method stub
			mListView.stopRefresh();
			mListView.stopLoadMore();
			
			L.v(TAG, "SearchCallBack", "-onFailure-" + error.toString());
			// 数据返回不正确 不允许上拉加载更多,允许下拉刷新
			mListView.setPullRefreshEnable(false);
			mListView.setEnableDragLoadMore(false);
			mListView.setPullRefreshEnable(true);
		}
		
	}
	
	private void updateLive(boolean isLocal, SpecllistRst t){
		
		L.v(TAG, "HorizontalCallBack", "-onSuccess-" + t.result);

		if (t.result == SUCCESS) {
			
			if(isFirst){
				
				if(!isLocal && isFix){
					sp.setAll(System.currentTimeMillis(), rstSerializer.toString(t));
				}
				
				liveList.clear();
				initSearch(t);
				getServerData(t);
				initWebview(t);
				initPoster(t);
				
			}
			
			frashColumnListView(t);
			loadNextPage(t);
			isFirst = false;
			
		} else {
			// 数据返回不正确 不允许上拉加载更多,允许下拉刷新
			mListView.setPullRefreshEnable(false);
			mListView.setEnableDragLoadMore(false);
			mListView.setPullRefreshEnable(true);
		}
	}
	
	/**
	 * 初始化"分类检索"
	 */
	private void initSearch(SpecllistRst t) {
//		// TODO Auto-generated method stub
//		/** 判断"分类检索"是否显示 */
//		if(t.label != null && t.label.isshow != null && t.label.isshow.equals("1")){
//			
//			/** 判断"分类检索"是否有栏目数据 */
//			if(t.cols != null && t.cols.colList != null && !t.cols.colList.isEmpty()){
//				filmSearch.initColumn(t.cols.colList);
//			}
//			
//			/** 判断"分类检索"是否有检索数据 */
//			if(t.label.lbs != null && !t.label.lbs.isEmpty()){
//				filmSearch.initSearch(t.label.lbs);
//			}
//			
//			tagView.setVisibility(View.VISIBLE);
//			filmSearch.setVisibility(View.VISIBLE);
//		}
		
		/** 判断"分类检索"是否显示 */
		if (t.label != null && t.label.isshow != null && t.label.isshow.equals("1")) {

			/** 判断"分类检索"是否有检索数据 */
			if (t.label.lbs != null && !t.label.lbs.isEmpty()) {
				filmSearch.initSearch(t.label.lbs);
				tagView.setVisibility(View.VISIBLE);
				filmSearch.setVisibility(View.VISIBLE);
			}

		}
		
		/** 判断"分类检索"是否有栏目数据 */
		if (t.cols != null && t.cols.colList != null && !t.cols.colList.isEmpty()) {
			filmSearch.initColumn(t.cols.colList);
			tagView.setVisibility(View.VISIBLE);
			filmSearch.setVisibility(View.VISIBLE);
		}
	}
	
	/**
	 * 初始化"Web专题"
	 */
	private void initWebview(SpecllistRst t) {
		/** 判断是否有"Web专题"数据 */
		if(t.cols != null && t.cols.colList != null && !t.cols.colList.isEmpty()){
			
			for (Col col : t.cols.colList) {
				if(col.type ==2){
					webUrl = col.url;
					webHight = col.h;
					break;
				}
			}
			
			if(!TextUtils.isEmpty(webUrl) && webHight >0){
				mWebView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, ScreenUtil.dp2px(webHight)));
				mWebView.setVisibility(View.VISIBLE);
				mWebView.loadUrl(webUrl);
			}else{
				mListView.removeHeaderView(mWebView);
			}
		}else{
			mListView.removeHeaderView(mWebView);
		}
	}

	
	/**
	 * 初始化海报页
	 */
	private void initPoster(SpecllistRst t) {
		// TODO Auto-generated method stub
		/** 判断当前海报是否显示 */
		if (t.showposter != null && t.showposter.equals("1") && t.poster != null && t.poster.cnts != null && t.poster.cnts.cntList != null  && !t.poster.cnts.cntList.isEmpty()) {
			poster.setVisibility(View.VISIBLE);
			poster.initData(false, shost, host, t.poster.cnts.cntList, PlayerFrom.BANNER_COLLECTION);
		}else{
			mListView.removeHeaderView(poster);
		}
			
	}
	
	/**
	 * 初始化服务器返回参数
	 */
	private void getServerData(SpecllistRst t) {
		// TODO Auto-generated method stub
		if(t.shost != null){
			shost = t.shost;
			L.v(TAG, "initServerInfo", "-shost-" + shost);
		}
		
		if(t.host != null){
			host = t.host;
			L.v(TAG, "initServerInfo", "-host-" + host);
		}
		
		if(t.label != null && t.label.clid != null){
			clid = t.label.clid;
			L.v(TAG, "initServerInfo", "-clid-" + clid);
		}
		
	}
	
	/**
	 * 刷新"列表"数据
	 */
	private void frashColumnListView(SpecllistRst t) {
		// TODO Auto-generated method stub
		if(t.cnts != null && t.cnts.cntList != null && !t.cnts.cntList.isEmpty()){
			
			for (Cnt cnt : t.cnts.cntList) {
				LiveInfo info = new LiveInfo();
				info.name = cnt.name;
				info.utp = cnt.utp;
				info.url = cnt.url;
				info.vgurl = cnt.url;
				info.xyzplayurl = cnt.url;
				info.ourl = cnt.ourl;
				info.btnply = cnt.btnply;
				info.weibourl = cnt.weibourl;
				info.pic1 = cnt.pic1;
				info.pic2 = cnt.pic2;
				info.exts = cnt.exts;
				info.hd = cnt.hd;
				
				
				liveList.add(info);
			}
			
			adapter.initData(shost, liveList);
			adapter.notifyDataSetChanged();
		}
	}
	
	/**
	 * 刷新"搜索"数据
	 */
	private void frashSearchListView(SearchRst t) {
		// TODO Auto-generated method stub
		if(t.cnts != null && t.cnts.cntList != null && !t.cnts.cntList.isEmpty()){
			for (com.fone.player.client.SearchRst.Cnt cnt : t.cnts.cntList) {
				LiveInfo info = new LiveInfo();
				info.name = cnt.name;
				info.pic1 = cnt.pic1;
				info.pic2 = cnt.pic2;
				info.utp = cnt.utp;
				info.url = cnt.url;
				info.vgurl = cnt.url;
				info.xyzplayurl = cnt.url;
//				info.exts = cnt.exts;
				
				liveList.add(info);
			}
			
			adapter.initData(shost, liveList);
			adapter.notifyDataSetChanged();
			mListView.setSelection(0);
		}
	}
	
	/** 
	 * 分类检索点击响应
	 */
	private class SearchListener implements OnSearcherListener{
		
		@Override
		public void onClick(String category, String country, String year, String attention) {
			
			L.v(TAG, "initFileSearch", "HorizontalActivity- category -" + category
					+ "- country -" + country + "- year -" + year
					+ "- attention -" + attention +"- clid -"+clid);
			
			//点击搜索
			if(TextUtils.isEmpty(attention)){
				
				setSearchData(category, country, year);
				page = 1;
				initSearchData(page);
				isColumn = false;
			}
			//点击栏目
			else{
				url = attention;
				initColumnData(url);
				isColumn = true;
			}
			isFirst = true;
			isFix = false;
		}

	}
	
	private void setSearchData(String category, String country, String year) {
		// TODO Auto-generated method stub
		this.category = category;
		this.country = country;
		this.year =year;
	}
	
	/** "搜索"是否存在下一页 . */
	private void loadNextPage(SearchRst t) {
		// TODO Auto-generated method stub
		if(t.rp != null && t.rp.m >= t.rp.p){
			page = t.rp.p;
			mListView.setEnableDragLoadMore(true);
			mListView.setPullLoadEnable(true);
		}else {
			// 隐藏上拉更多
			mListView.setEnableDragLoadMore(false);
			mListView.setPullLoadEnable(false);
		}
	}
	
	/** "栏目"是否存在下一页 . */
	private void loadNextPage(SpecllistRst t) {
		// TODO Auto-generated method stub
		if(t.rp != null && t.rp.m == 1 && t.rp.nurl != null){
			nurl = t.rp.nurl;
			mListView.setEnableDragLoadMore(true);
			mListView.setPullLoadEnable(true);
		}else {
			// 隐藏上拉更多
			mListView.setEnableDragLoadMore(false);
			mListView.setPullLoadEnable(false);
		}
	}
	
	private class LiveItemClicker implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// 判断网络状态
			if (FoneUtil.isNetOk(LiveActivity.this)) {
				HeaderViewListAdapter hdAdapter = (HeaderViewListAdapter) mListView.getAdapter();
				LiveInfo info = (LiveInfo) hdAdapter.getWrappedAdapter().getItem((int) id);

				L.v(TAG, "LiveItemClicker", info.name);
				Activity2poster.startActivity(LiveActivity.this,getRedirectInfo(info));
			}
			
		}
	}
	
	private RedirectInfo getRedirectInfo(LiveInfo info){
		RedirectInfo redirectInfo = new RedirectInfo();
		redirectInfo.host = host;
		redirectInfo.utp = info.utp;
		redirectInfo.weibourl = info.weibourl;
		redirectInfo.url = info.url;
		redirectInfo.vgurl = info.url;
		redirectInfo.xyzplayurl = info.url;
		redirectInfo.dnfs = info.dfnt;
		redirectInfo.name = info.name;
		redirectInfo.ourl = info.ourl;
		redirectInfo.btnply = info.btnply;
		redirectInfo.pic = info.pic2;
		return redirectInfo;
	}

	@Override
	public void onRefresh() {
		// TODO 下拉刷新
		page = 1;
		mListView.onLoad();
		//如果"栏目"下拉刷新
		if(isColumn && initColumnData(url)){
			isFirst = true;
		}
		//如果"搜索"下拉刷新
		else if(!isColumn && initSearchData(page)){
			isFirst = true;
		}
	}

	@Override
	public void onLoadMore() {
		// TODO 上拉更多
		//如果"栏目"下拉刷新
		if(isColumn && initColumnData(nurl)){
			mListView.setEnableDragLoadMore(false);
		}
		//如果"搜索"下拉刷新
		else if (!isColumn && initSearchData(page)) {
			L.v(TAG, "onLoadMore", "-page:-"+page);
			mListView.setEnableDragLoadMore(false);
		}else{
			mListView.setEnableDragLoadMore(true);
			mListView.setPullLoadEnable(true);
		}
	}

	private class BtnOnClicker implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.common_title_left_bt:
				finish();
				break;
				
			default:
				break;
			}
		}
		
	}
	

}
